//
//  RZVoiceRecordControl.m
//  RZIM
//
//  Created by reyzhang on 2021/8/18.
//

#import "RZVoiceRecordControl.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>


#import "RZVoiceCaptureView.h"
//#import "RZVoicePlayer.h"
#import "RZKitCommonDefine.h"

@interface RZVoiceRecordControl () <RZVoiceCaptureViewDelegate>

@property (nonatomic, strong) RZVoiceCaptureView *voiceCaptureView;
@property (nonatomic, assign) BOOL isAudioRecoderTimeOut;
@end

@implementation RZVoiceRecordControl

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.isAudioRecoderTimeOut = NO;
        [self registerNotification];
    }
    return self;
}

//语音消息开始录音
- (void)onBeginRecordEvent {
    if (self.voiceCaptureView) {
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(recordWillBegin)]) {
        if (![self.delegate recordWillBegin]) {
            return;
        }
    }


    [self checkRecordPermission:^{
        self.voiceCaptureView =
            [[RZVoiceCaptureView alloc] initWithFrame:
             CGRectMake(0, 20,
                        [UIScreen mainScreen].bounds.size.width,
                        [UIScreen mainScreen].bounds.size.height)];
        
        self.voiceCaptureView.delegate = self;
//        if ([RZVoicePlayer defaultPlayer].isPlaying) {
//            [[RCVoicePlayer defaultPlayer] resetPlayer];
//        }
        [self.voiceCaptureView startRecord];
        if ([self.delegate respondsToSelector:@selector(voiceRecordControlDidBegin:)]) {
            [self.delegate voiceRecordControlDidBegin:self];
        }
    }];
}

//语音消息录音结束
- (void)onEndRecordEvent {
    if (!self.voiceCaptureView) {
        return;
    }

    NSData *recordData = [self.voiceCaptureView stopRecord];
    if (self.voiceCaptureView.duration > 1.0f && nil != recordData) {
        if ([self.delegate respondsToSelector:@selector(voiceRecordControl:didEnd:recordFile:duration:error:)]) {
            
            [self.delegate voiceRecordControl:self
                                       didEnd:recordData
                                   recordFile:self.voiceCaptureView.recordFile
                                     duration:self.voiceCaptureView.duration
                                        error:nil];
        }
        [self destroyVoiceCaptureControl];
    } else {
        // message too short
        if (!self.isAudioRecoderTimeOut) {
            self.isAudioRecoderTimeOut = NO;
            [self.voiceCaptureView showMsgShortView];
            [self performSelector:@selector(destroyVoiceCaptureControl) withObject:nil afterDelay:1.0f];
            if ([self.delegate respondsToSelector:@selector(voiceRecordControlDidCancel:)]) {
                [self.delegate voiceRecordControlDidCancel:self];
            }
        }
    }
}

//滑出显示
- (void)dragExitRecordEvent {
    [self.voiceCaptureView showCancelView];
}

- (void)dragEnterRecordEvent {
    [self.voiceCaptureView hideCancelView];
}

- (void)onCancelRecordEvent {
    if (self.voiceCaptureView) {
        if ([self.delegate respondsToSelector:@selector(voiceRecordControlDidCancel:)]) {
            [self.delegate voiceRecordControlDidCancel:self];
        }
        [self.voiceCaptureView cancelRecord];
        [self destroyVoiceCaptureControl];
    }
}

#pragma mark - RZVoiceCaptureControlDelegate
- (void)RZVoiceCaptureViewTimeout:(double)duration {
    self.isAudioRecoderTimeOut = YES;
    [self onEndRecordEvent];
}

- (void)RZVoiceCaptureViewTimeUpdate:(double)duration {
}

#pragma mark - Notification
- (void)registerNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(audioSessionInterrupted:)
        name:AVAudioSessionInterruptionNotification
      object:nil];
}

- (void)audioSessionInterrupted:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType interruptionType = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    switch (interruptionType) {
    case AVAudioSessionInterruptionTypeBegan: {
        [self onEndRecordEvent];
    } break;
    default:
        break;
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Private
- (void)destroyVoiceCaptureControl {
    [self.voiceCaptureView stopTimer];
    [self.voiceCaptureView removeFromSuperview];
    self.voiceCaptureView = nil;
    self.isAudioRecoderTimeOut = NO;
}

- (void)checkRecordPermission:(void (^)(void))successBlock {
    if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) {
        if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(recordPermission)]) {
            if ([AVAudioSession sharedInstance].recordPermission == AVAudioSessionRecordPermissionGranted) {
                successBlock();
            } else if ([AVAudioSession sharedInstance].recordPermission == AVAudioSessionRecordPermissionDenied) {
                [self alertRecordPermissionDenied];
            } else if ([AVAudioSession sharedInstance].recordPermission == AVAudioSessionRecordPermissionUndetermined) {
                [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                    if (!granted) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self alertRecordPermissionDenied];
                        });
                    };
                }];
            }
        }
    } else {
        successBlock();
    }
}

- (void)alertRecordPermissionDenied {
    //TODO:showAlert
}

@end
